package com.example.myblog.config;

import com.example.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * Spring Security 配置类
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig {

    @Autowired
    private UserService userService;
    
    // PasswordEncoder已移至PasswordConfig类，解决循环依赖问题
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    /**
     * 认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
                .userDetailsService(userService)
                .passwordEncoder(passwordEncoder)
                .and()
                .build();
    }
    
    /**
     * 安全过滤器链配置
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                // 公开访问的资源
                .requestMatchers("/", "/posts/{id}", "/css/**", "/js/**", "/images/**", "/login", "/category/{id}", "/about", "/treasure").permitAll()
                .requestMatchers("/treasure/preview/**", "/treasure/download/**").permitAll()
                // 开放智能助手接口（无需登录）
                .requestMatchers("/api/assistant/**").permitAll()
                // 需要管理员权限的资源
                .requestMatchers("/posts/new", "/posts/{id}/edit", "/posts/{id}/delete", "/admin/**", "/api/upload-image").hasRole("ADMIN")
                // 其他所有请求需要认证
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .defaultSuccessUrl("/admin", true)
                .permitAll()
            )
            .logout(logout -> logout
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/")
                .permitAll()
            )
            .rememberMe(remember -> remember
                .key("uniqueAndSecretKey")
                .tokenValiditySeconds(86400) // 1天
            )
            .csrf(csrf -> csrf
                // 禁用文件上传和智能助手接口的CSRF保护
                .ignoringRequestMatchers("/admin/treasure/file", "/admin/treasure/website", "/api/upload-image", "/api/assistant/**")
            )
            .headers(headers -> headers
                .frameOptions(frame -> frame.sameOrigin())
            );
        
        return http.build();
    }
}